package project.dade.cn.bst.fragments;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.pgyersdk.update.PgyUpdateManager;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.bingoogolapple.bgabanner.BGABanner;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import project.dade.cn.bst.R;
import project.dade.cn.bst.activity.GoshoppingActivity;
import project.dade.cn.bst.activity.HotsActivity;
import project.dade.cn.bst.activity.ImageGalleryActivity;
import project.dade.cn.bst.activity.ProductDtailActivity;
import project.dade.cn.bst.activity.SearchActivity;
import project.dade.cn.bst.activity.WashActivity;
import project.dade.cn.bst.activity.WashCarActivity;
import project.dade.cn.bst.adapter.base.IndexNewsAdapter;
import project.dade.cn.bst.base.ParentFragment;
import project.dade.cn.bst.manager.ApiConfig;
import project.dade.cn.bst.model.BaseRequestModel;
import project.dade.cn.bst.model.IndexInfoBanners;
import project.dade.cn.bst.model.IndexInfoData;
import project.dade.cn.bst.model.IndexInfoHots;
import project.dade.cn.bst.network.callback.ResultCallback;
import project.dade.cn.bst.network.request.OkHttpRequest;
import project.dade.cn.bst.newIndex.PullableScrollView;
import project.dade.cn.bst.utils.AppUtil;
import project.dade.cn.bst.utils.LogUtil;
import project.dade.cn.bst.utils.NetRequestUtil;
import project.dade.cn.bst.utils.ToastUtil;
import project.dade.cn.bst.views.EmptyLayout;
import project.dade.cn.bst.views.GridViewInScroll;


public class IndexFragment extends ParentFragment implements View.OnClickListener, AdapterView.OnItemClickListener,BGABanner.Adapter{
    public static String FRAGMENT_TAG = IndexFragment.class.getSimpleName();
    @InjectView(R.id.errorLayout)
    EmptyLayout mErrorLayout;
    @InjectView(R.id.banner_main_depth)
    public BGABanner mDefaultBanner;
    @InjectView(R.id.arrgent)
    GridViewInScroll mGridView;
    @InjectView(R.id.indexQuick1)
    TextView indexQuick1;
    @InjectView(R.id.indexQuick2)
    TextView indexQuick2;
    @InjectView(R.id.indexQuick3)
    TextView indexQuick3;
    @InjectView(R.id.indexQuick4)
    TextView indexQuick4;
    @InjectView(R.id.indexQuick5)
    TextView indexQuick5;
    @InjectView(R.id.indexQuick6)
    TextView indexQuick6;
    @InjectView(R.id.boutique1)
    ImageView Boutique1;
    @InjectView(R.id.boutique2)
    ImageView Boutique2;
    @InjectView(R.id.boutique3)
    ImageView Boutique3;
    @InjectView(R.id.toprela)
    LinearLayout top;
    @InjectView(R.id.search)
    LinearLayout search;
    @InjectView(R.id.listview_placemore)
    public PullableScrollView scrollview;
    private ScrollView myPager;
    private LinearLayout rl_title;
    //轮播图数据
    List<IndexInfoBanners> bannerLists;
    //轮播图集合
    private List<View> mDepthViews;
    //精品推荐数据
    LinkedList<IndexInfoHots> boutiques;
    //新品数据
    private List<IndexInfoHots> news;
    //热卖区
    private  List<IndexInfoHots> hots;
    private IndexNewsAdapter mAdapter;
    private  BaseRequestModel model;
    @InjectView(R.id.rl_recyclerview_refresh)
   SwipeRefreshLayout mSwipeRefreshLayout; // 下拉刷新


    @Override
    public int setRootViewID() {
        return 0;
    }

    @Override
    public void findView(View rootView) {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.activity_main, null);
        ButterKnife.inject(this, v);
        initRequest();
        mAdapter = new IndexNewsAdapter(getActivity());
        mAdapter.setDatas(news);
        mGridView.setAdapter(mAdapter);
        mGridView.setOnItemClickListener(this);
        indexQuick1.setOnClickListener(this);
        indexQuick2.setOnClickListener(this);
        indexQuick3.setOnClickListener(this);
        indexQuick4.setOnClickListener(this);
        indexQuick5.setOnClickListener(this);
        indexQuick6.setOnClickListener(this);
        Boutique1.setOnClickListener(this);
        Boutique2.setOnClickListener(this);
        Boutique3.setOnClickListener(this);
        search.setOnClickListener(this);
        initRequest();
        myPager = (PullableScrollView) v.findViewById(R.id.listview_placemore);
        rl_title = (LinearLayout) v.findViewById(R.id.toprela);
        scrollview = (PullableScrollView) v.findViewById(R.id.listview_placemore);
        //获取焦点
        mDefaultBanner.setFocusable(true);
        mDefaultBanner.setFocusableInTouchMode(true);
        mDefaultBanner.requestFocus();

        rl_title.getBackground().setAlpha(0);
        scrollview.setOnScrollChangedListener(new PullableScrollView.OnScrollChangedListener() {

            @Override
            public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {
                // TODO Auto-generated method stub
                if (myPager != null && myPager.getHeight() > 0) {
                    //define it for scroll height
                    int lHeight = myPager.getHeight();
                    if (t < lHeight) {
                        int progress = (int) (new Float(t) / new Float(lHeight) * 200);
                        rl_title.getBackground().setAlpha(progress);

                    } else {
                        rl_title.getBackground().setAlpha(255 - 55);

                    }
                }
            }
        });



        mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_purple, android.R.color.holo_blue_bright, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                if (AppUtil.isNetworkAvailable(getActivity())) {
                    requestGetindex();
                } else {
                    Snackbar.make(getView(),"网络连接失败", Snackbar.LENGTH_SHORT).show();
                }
            }
        });
        PgyUpdateManager.register(getActivity());
        return v;
    }



    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    //acticity生命周期，进入这个页面的时候调取接口
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }


    private void initRequest() {
        if (AppUtil.isNetworkAvailable(getActivity())) {
            mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            requestGetindex();
        } else {
//            mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
            Snackbar.make(getView(),"网络连接失败", Snackbar.LENGTH_SHORT).show();

        }

    }

    private void requestGetindex() {
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.index)
                .get(new ResultCallback<String>() {
                    @Override
                    public void onError(com.squareup.okhttp.Request request, Exception e) {
                        top.setVisibility(View.VISIBLE);
                        mSwipeRefreshLayout.setRefreshing(false);
                        mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    }
                    @Override
                    public void onResponse(String response) {
                        mSwipeRefreshLayout.setRefreshing(false);
                      mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                        top.setVisibility(View.VISIBLE);
                        model = JSON.parseObject(response, BaseRequestModel.class);
                        if (model != null && model.getResult() == 0) {
                            IndexInfoData infoData = model.getData();
                            bannerLists = new LinkedList<IndexInfoBanners>();
                            bannerLists = infoData.getBanners();
                            loadData(mDefaultBanner, bannerLists.size());
                            //  精品推荐
                            if (infoData.getBoutiques().size() > 0) {
                                boutiques = infoData.getBoutiques();

                                //为你而选
                                if (infoData.getNews().size() > 0) {
                                    news = infoData.getNews();
                                    LogUtil.i(TAG, "图片地址：" + news);
                                    mAdapter.setDatas(news);
                                }
                            }

                        } else {
                            mSwipeRefreshLayout.setRefreshing(false);
                            top.setVisibility(View.VISIBLE);

                            ToastUtil.showShort(getActivity(), NetRequestUtil.requestsError(response, "获取数据失败"));
                        }


                    }

                    private void loadData(final BGABanner banner, int count) {
                        banner.setAdapter(IndexFragment.this);
                        banner.setData(bannerLists,null);
                    }
                });


    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.indexQuick1:
                Intent mIntent = new Intent(getActivity(),
                        WashCarActivity.class);
                startActivity(mIntent);
                break;
            case R.id.indexQuick2:
                Snackbar.make(getView(), R.string.expect, Snackbar.LENGTH_SHORT).show();
                break;
            case R.id.indexQuick3:
                Snackbar.make(getView(), R.string.expect, Snackbar.LENGTH_SHORT).show();

                break;
            case R.id.indexQuick4:
                redirectToPage(GoshoppingActivity.class);
                break;
            case R.id.indexQuick5:
                Snackbar.make(getView(), R.string.expect, Snackbar.LENGTH_SHORT).show();

                break;
            case R.id.indexQuick6:
                Snackbar.make(getView(), R.string.expect, Snackbar.LENGTH_SHORT).show();

                break;

            case R.id.search:
                redirectToPage(SearchActivity.class);
                break;
            case R.id.boutique1:
                LinkedList<IndexInfoHots> hots=  model.getData().getHots();
                Intent intent = new Intent(getActivity(), HotsActivity.class);
                intent.putExtra("hots", hots);
               getActivity().startActivity(intent);
                break;

        }


    }

    /**
     * 跳转相关页功能
     *
     * @param <T>
     */
    private <T> void redirectToPage(Class<T> class1) {

        startActivity(new Intent(getActivity(), class1));

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent mIntentRegInfo = new Intent(getActivity(), ProductDtailActivity.class);
        mIntentRegInfo.putExtra("id", mAdapter.getItem(position).getProductId());
        startActivity(mIntentRegInfo);

    }

    @Override
    public void fillBannerItem(BGABanner banner, View view, Object model, int position) {

            Glide.with(getActivity())
                .load(bannerLists.get(position).getAdsImage())
                .placeholder(R.drawable.default_image)
                .error(R.drawable.default_image)
                .into((ImageView)view);
    }

}
